package com.rrd.itext.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.rrd.itext.utils.GlobalNames;

public class ShowTemplateServlet extends HttpServlet{
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = null;
        try {
            out = response.getWriter(); 
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String templateName = request.getParameter("templateName");
        if(templateName == null || "".equals(templateName)){
            out.write("Please select a template.");
            return;
        }
        String path = request.getSession().getServletContext().getRealPath("resources") + "\\" + templateName;
        File templateDir = new File(path);
        if (!templateDir.exists()) {
           out.print("The selected template doesn't exist.");
           return;
        }
        File layoutFile = new File(path + "\\" + GlobalNames.LAYOUT_FILE_NAME);
        BufferedReader layoutBR = new BufferedReader(new InputStreamReader(new FileInputStream(layoutFile), "UTF-8"));
        
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = layoutBR.readLine()) != null){
          buffer.append(line);
        } 
        request.setAttribute("layoutXML", buffer.toString());
        ServletContext sc = getServletContext();
        RequestDispatcher rd = sc.getRequestDispatcher("/editLayout.jsp");
        rd.forward(request, response);
    }
}
